package br.unipar.blog.mobile;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

public class HelloWorldWebForm extends Form implements CommandListener {
    
    private final UniparBlogMidlet midlet;
    
    Command sairCommand, acessarCommand;
    
    TextField respostaTextField;

    public HelloWorldWebForm(UniparBlogMidlet midlet) {
        super("Teste Comunicacao Web");
        this.midlet = midlet;
        
        sairCommand = new Command("Sair", Command.EXIT, 0);
        acessarCommand = new Command("Acessar", Command.SCREEN, 0);
        
        addCommand(sairCommand);
        addCommand(acessarCommand);
        
        setCommandListener(this);
        
        respostaTextField = new TextField("Resposta", "", 50, TextField.PLAIN);
        append(respostaTextField);
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command == sairCommand) {
            midlet.destroyApp(true);
        } else if (command == acessarCommand) {
            Form carregandoForm = new Form("Carregando ...");
            midlet.display.setCurrent(carregandoForm);
            Thread acessarThread = new Thread() {
                public void run() {
                    acessarWeb();
                }
            };
            acessarThread.start();
        }
    }
    
    public void acessarWeb() {
        try {
            String url = "http://localhost:8080/unipar-blog-view-jsf/"
                    + "ws/autenticar/hello";
            HttpConnection connection = 
                    (HttpConnection) Connector.open(url, Connector.READ_WRITE);
            connection.setRequestMethod(HttpConnection.GET);
            
            String resposta = connection.getResponseMessage();
            respostaTextField.setString(resposta);
            
            connection.close();
            
            midlet.display.setCurrent(midlet.helloWorldWebForm);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
}
